package com.tcs.es.sql;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.Properties;

/**
 * @ClassName : EsSql
 * @Author : 神经刀
 * @Date : 2019/6/6 : 20:08
 * @Version : 1.0
 */
public class EsSqlJDBC {

    private final static Logger logger = LoggerFactory.getLogger(EsSqlJDBC.class);

    String driver = "org.elasticsearch.xpack.sql.jdbc.jdbc.JdbcDriver";
    String elasticsearchAddress = "192.168.100.24:9200";

    public Properties connectionProperties() {
        Properties properties = new Properties();
//        properties.put("user", "test_admin");
//        properties.put("password", "x-pack-test-password");
        return properties;
    }

    @Test
    public void test() {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            logger.error("", e);
        }
        String address = "jdbc:es://http://" + elasticsearchAddress;
        Properties connectionProperties = connectionProperties();
        try {
            Connection connection = DriverManager.getConnection(address, connectionProperties);
            Statement statement = connection.createStatement();
            ResultSet results = statement.executeQuery("SELECT postDate,message,user FROM mess");
            while (results.next()) {
                logger.info("postDate : {} , message : {} , user : {}",
                        results.getString("postDate"), results.getString("message"), results.getString("user"));
            }
        } catch (SQLException e) {
            logger.error("", e);
        } catch (Exception e) {
            logger.error("", e);
        }
    }
}